<?php

namespace app\controller\sys;

use app\BaseController;
use app\model\AdminAccount;
use app\model\SysRole;
use think\facade\Config;
use think\Response;

class Admin extends BaseController
{
    public function login(): Response
    {
        return $this->success($this->app->make(AdminAccount::class)->login());
    }

    public function check(): Response
    {
        $admin = $this->request->admin->toArray();
        if (!empty($admin['role'])) {
            $role = $this->app->make(SysRole::class)->whereIn("id", $admin['role'])->where('state', 1)->field("menu_lst")->select()->toArray();
            if (!empty($role)) {
                foreach ($role as $item) {
                    $admin['role_lst'] = array_merge($admin['role_lst'] ?? [], $item['menu_lst']);
                }
            }
        }
        return $this->success($admin);
    }

    public function auth()
    {
        $admin = $this->request->admin;
        $power = $this->request->param("power");
        $pubConfig = Config::get("menu.public");
        if ($admin['type'] == 1 || in_array($power, $pubConfig)) return $this->success();
        $private = Config::get("menu.private");
        if (in_array($power, $private) || empty($admin['role'])) throw new \Exception("无访问权限");
        $role = $this->app->make(SysRole::class)->whereIn("id", $admin['role'])->where('state', 1)->field("menu_lst")->select()->toArray();
        if (empty($role)) throw new \Exception("无访问权限");
        $its = [];
        foreach ($role as $item) {
            $its = array_merge($its, $item['menu_lst']);
        }
        if (!in_array($power, $its)) throw new \Exception("无访问权限");
        return $this->success();
    }

    public function modify(): Response
    {
        $user = $this->request->admin;
        $post = $this->request->post();
        if (!checkPassword($post['oldPassword'], $user['token'], $user['password'])) throw new \Exception("原密码错误", 7001);
        $password = setPassword($post['newPassword']);
        $user->password = $password['password'];
        $user->token = $password['token'];
        $user->save();
        return $this->success();
    }
}
